<template>
  <div class="users-container">
    <!-- 搜索和过滤区域 -->
    <div class="search-section neu-card">
      <div class="search-form">
        <div class="search-input">
          <input 
            type="text" 
            v-model="searchQuery.keyword" 
            class="neu-input" 
            placeholder="搜索用户名、姓名或邮箱"
            @keyup.enter="handleSearch"
          />
          <button class="neu-button primary" @click="handleSearch">
            <el-icon><Search /></el-icon>
            搜索
          </button>
        </div>
        
        <div class="filter-options">
          <div class="filter-item">
            <label>角色</label>
            <el-select v-model="searchQuery.role" placeholder="全部角色" class="filter-select">
              <el-option label="全部角色" value="" />
              <el-option label="管理员" value="admin" />
              <el-option label="普通用户" value="user" />
            </el-select>
          </div>
          
          <button class="neu-button" @click="resetFilters">
            重置筛选
          </button>
        </div>
      </div>
    </div>
    
    <!-- 操作按钮区域 -->
    <div class="actions-section">
      <button class="neu-button primary" @click="showAddUserDialog">
        <el-icon><Plus /></el-icon>
        添加用户
      </button>
    </div>
    
    <!-- 用户列表 -->
    <div class="users-list neu-card">
      <el-table 
        :data="users" 
        style="width: 100%" 
        v-loading="loading"
        class="neu-table-wrapper"
      >
        <el-table-column prop="username" label="用户名" min-width="120" />
        <el-table-column prop="name" label="姓名" min-width="120" />
        <el-table-column prop="role" label="角色" width="100">
          <template #default="scope">
            <span class="role-tag" :class="scope.row.role === 'admin' ? 'admin' : 'user'">
              {{ scope.row.role === 'admin' ? '管理员' : '普通用户' }}
            </span>
          </template>
        </el-table-column>
        <el-table-column prop="email" label="邮箱" min-width="180" />
        <el-table-column prop="phone" label="电话" min-width="150" />
        <el-table-column prop="createTime" label="注册时间" min-width="120" />
        <el-table-column label="操作" width="200" fixed="right">
          <template #default="scope">
            <div class="table-actions">
              <button class="action-btn view" @click="viewUserDetails(scope.row)">
                <el-icon><View /></el-icon>
                详情
              </button>
              <button class="action-btn edit" @click="editUser(scope.row)">
                <el-icon><Edit /></el-icon>
                编辑
              </button>
              <button 
                class="action-btn delete" 
                @click="confirmDeleteUser(scope.row)"
                :disabled="scope.row.id === 1 || store.user.id === scope.row.id"
              >
                <el-icon><Delete /></el-icon>
                删除
              </button>
            </div>
          </template>
        </el-table-column>
      </el-table>
      
      <!-- 分页 -->
      <div class="pagination-container">
        <el-pagination
          v-model:current-page="currentPage"
          v-model:page-size="pageSize"
          :page-sizes="[10, 20, 50, 100]"
          layout="total, sizes, prev, pager, next, jumper"
          :total="total"
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
        />
      </div>
    </div>
    
    <!-- 添加/编辑用户对话框 -->
    <el-dialog
      v-model="userDialogVisible"
      :title="isEditMode ? '编辑用户' : '添加用户'"
      width="500px"
      class="neu-dialog"
    >
      <el-form :model="userForm" label-width="80px" :rules="userRules" ref="userFormRef">
        <el-form-item label="用户名" prop="username">
          <el-input v-model="userForm.username" placeholder="请输入用户名" :disabled="isEditMode" />
        </el-form-item>
        
        <el-form-item label="姓名" prop="name">
          <el-input v-model="userForm.name" placeholder="请输入姓名" />
        </el-form-item>
        
        <el-form-item label="邮箱" prop="email">
          <el-input v-model="userForm.email" placeholder="请输入邮箱" />
        </el-form-item>
        
        <el-form-item label="电话" prop="phone">
          <el-input v-model="userForm.phone" placeholder="请输入电话" />
        </el-form-item>
        
        <el-form-item label="角色" prop="role">
          <el-select v-model="userForm.role" placeholder="请选择角色" style="width: 100%">
            <el-option label="管理员" value="admin" />
            <el-option label="普通用户" value="user" />
          </el-select>
        </el-form-item>
        
        <el-form-item v-if="!isEditMode" label="密码" prop="password">
          <el-input v-model="userForm.password" type="password" placeholder="请输入密码" show-password />
        </el-form-item>
      </el-form>
      
      <template #footer>
        <div class="dialog-footer">
          <button class="neu-button" @click="userDialogVisible = false">取消</button>
          <button class="neu-button primary" @click="submitUserForm">确认</button>
        </div>
      </template>
    </el-dialog>
    
    <!-- 用户详情对话框 -->
    <el-dialog
      v-model="detailsDialogVisible"
      title="用户详情"
      width="500px"
      class="neu-dialog"
    >
      <div v-if="selectedUser" class="user-details">
        <div class="detail-item">
          <span class="label">用户名:</span>
          <span class="value">{{ selectedUser.username }}</span>
        </div>
        
        <div class="detail-item">
          <span class="label">姓名:</span>
          <span class="value">{{ selectedUser.name }}</span>
        </div>
        
        <div class="detail-item">
          <span class="label">角色:</span>
          <span class="value" :class="selectedUser.role === 'admin' ? 'role-admin' : 'role-user'">
            {{ selectedUser.role === 'admin' ? '管理员' : '普通用户' }}
          </span>
        </div>
        
        <div class="detail-item">
          <span class="label">邮箱:</span>
          <span class="value">{{ selectedUser.email }}</span>
        </div>
        
        <div class="detail-item">
          <span class="label">电话:</span>
          <span class="value">{{ selectedUser.phone || '未设置' }}</span>
        </div>
        
        <div class="detail-item">
          <span class="label">注册时间:</span>
          <span class="value">{{ selectedUser.createTime }}</span>
        </div>
      </div>
    </el-dialog>
    
    <!-- 删除确认对话框 -->
    <el-dialog
      v-model="deleteDialogVisible"
      title="删除确认"
      width="400px"
      class="neu-dialog"
    >
      <div class="delete-dialog-content">
        <p>确认删除用户 {{ selectedUser?.username }} ？</p>
        <p class="warning-text">此操作不可恢复，请谨慎操作！</p>
      </div>
      
      <template #footer>
        <div class="dialog-footer">
          <button class="neu-button" @click="deleteDialogVisible = false">取消</button>
          <button class="neu-button danger" @click="confirmDelete">确认删除</button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, onMounted } from 'vue'
import { Search, Plus, View, Edit, Delete } from '@element-plus/icons-vue'
import { ElMessage } from 'element-plus'
import { userService } from '../api/services'
import store from '../store'

// 搜索和筛选
const searchQuery = ref({
  keyword: '',
  role: ''
})

// 分页参数
const currentPage = ref(1)
const pageSize = ref(10)
const total = ref(0)

// 用户列表
const users = ref([])
const loading = ref(false)

// 对话框状态
const userDialogVisible = ref(false)
const detailsDialogVisible = ref(false)
const deleteDialogVisible = ref(false)
const isEditMode = ref(false)
const selectedUser = ref(null)

// 表单数据
const userForm = ref({
  username: '',
  name: '',
  email: '',
  phone: '',
  role: 'user',
  password: ''
})

// 表单验证规则
const userRules = {
  username: [
    { required: true, message: '请输入用户名', trigger: 'blur' },
    { min: 3, max: 20, message: '长度在 3 到 20 个字符', trigger: 'blur' }
  ],
  name: [
    { required: true, message: '请输入姓名', trigger: 'blur' }
  ],
  email: [
    { required: true, message: '请输入邮箱', trigger: 'blur' },
    { type: 'email', message: '请输入正确的邮箱地址', trigger: 'blur' }
  ],
  role: [
    { required: true, message: '请选择角色', trigger: 'change' }
  ],
  password: [
    { required: true, message: '请输入密码', trigger: 'blur' },
    { min: 6, message: '密码长度不能小于6位', trigger: 'blur' }
  ]
}

// 获取用户列表
const fetchUsers = async () => {
  try {
    loading.value = true
    const response = await userService.getUsers({
      page: currentPage.value,
      pageSize: pageSize.value,
      ...searchQuery.value
    })
    
    if (response.code === 200) {
      users.value = response.data.list
      total.value = response.data.total
    }
  } catch (error) {
    console.error('获取用户列表失败:', error)
    ElMessage.error('获取用户列表失败')
  } finally {
    loading.value = false
  }
}

// 搜索用户
const handleSearch = () => {
  currentPage.value = 1
  fetchUsers()
}

// 重置筛选
const resetFilters = () => {
  searchQuery.value = {
    keyword: '',
    role: ''
  }
  currentPage.value = 1
  fetchUsers()
}

// 显示添加用户对话框
const showAddUserDialog = () => {
  isEditMode.value = false
  userForm.value = {
    username: '',
    name: '',
    email: '',
    phone: '',
    role: 'user',
    password: ''
  }
  userDialogVisible.value = true
}

// 显示编辑用户对话框
const editUser = (user) => {
  isEditMode.value = true
  userForm.value = {
    ...user,
    password: ''
  }
  userDialogVisible.value = true
}

// 查看用户详情
const viewUserDetails = (user) => {
  selectedUser.value = user
  detailsDialogVisible.value = true
}

// 显示删除确认对话框
const confirmDeleteUser = (user) => {
  selectedUser.value = user
  deleteDialogVisible.value = true
}

// 提交用户表单
const submitUserForm = async () => {
  try {
    if (isEditMode.value) {
      const response = await userService.updateUser(userForm.value.id, userForm.value)
      if (response.code === 200) {
        ElMessage.success('更新成功')
        userDialogVisible.value = false
        fetchUsers()
      }
    } else {
      const response = await userService.createUser(userForm.value)
      if (response.code === 200) {
        ElMessage.success('添加成功')
        userDialogVisible.value = false
        fetchUsers()
      }
    }
  } catch (error) {
    console.error('操作失败:', error)
    ElMessage.error('操作失败')
  }
}

// 确认删除用户
const confirmDelete = async () => {
  try {
    const response = await userService.deleteUser(selectedUser.value.id)
    if (response.code === 200) {
      ElMessage.success('删除成功')
      deleteDialogVisible.value = false
      fetchUsers()
    }
  } catch (error) {
    console.error('删除失败:', error)
    ElMessage.error('删除失败')
  }
}

// 分页处理
const handleSizeChange = (val) => {
  pageSize.value = val
  fetchUsers()
}

const handleCurrentChange = (val) => {
  currentPage.value = val
  fetchUsers()
}

// 初始化
onMounted(() => {
  fetchUsers()
})
</script>

<style scoped>
@import '../assets/styles/neumorphism.css';

.users-container {
  display: flex;
  flex-direction: column;
  gap: 20px;
}

.search-section {
  padding: 20px;
}

.search-form {
  display: flex;
  justify-content: space-between;
  align-items: center;
  flex-wrap: wrap;
  gap: 20px;
}

.search-input {
  display: flex;
  gap: 10px;
  flex: 1;
}

.filter-options {
  display: flex;
  gap: 20px;
  align-items: center;
}

.filter-item {
  display: flex;
  align-items: center;
  gap: 10px;
}

.filter-select {
  width: 150px;
}

.actions-section {
  display: flex;
  justify-content: flex-end;
}

.table-actions {
  display: flex;
  gap: 8px;
}

.action-btn {
  display: inline-flex;
  align-items: center;
  gap: 5px;
  padding: 6px 12px;
  border: none;
  border-radius: 6px;
  cursor: pointer;
  transition: all 0.3s ease;
  font-size: 14px;
}

.action-btn.view {
  background-color: var(--primary-blue-light);
  color: var(--primary-blue);
}

.action-btn.edit {
  background-color: var(--warning-light);
  color: var(--warning);
}

.action-btn.delete {
  background-color: var(--danger-light);
  color: var(--danger);
}

.action-btn:hover {
  filter: brightness(0.9);
}

.action-btn:disabled {
  opacity: 0.5;
  cursor: not-allowed;
}

.role-tag {
  padding: 4px 8px;
  border-radius: 4px;
  font-size: 12px;
}

.role-tag.admin {
  background-color: var(--primary-blue-light);
  color: var(--primary-blue);
}

.role-tag.user {
  background-color: var(--success-light);
  color: var(--success);
}

.user-details {
  display: flex;
  flex-direction: column;
  gap: 15px;
}

.detail-item {
  display: flex;
  gap: 10px;
}

.detail-item .label {
  color: var(--text-secondary);
  min-width: 80px;
}

.detail-item .value {
  color: var(--text-primary);
}

.warning-text {
  color: var(--danger);
  margin-top: 10px;
}

.dialog-footer {
  display: flex;
  justify-content: flex-end;
  gap: 10px;
  margin-top: 20px;
}
</style>